<?php

// 后台登录类

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use DB;
use Session;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }
	
	// 登录页
	public function login()
    {
		// 登录页面
        return view("login");
    }
	
	// 验证登录信息
	public function checkLogin(Request $request)
    {
		$data = $request -> except('_token');
		$admin_info = DB::table('admin')
						// 账号
						->where( 'name','=',$data['name'] )
						// 密码
						->where( 'pass','=',$data['pass'] )
						->first();
		// 验证通过
		if( $admin_info )
		{
			$admin_id = $admin_info->id;
			// 1. 把用户信息放到 session 里
			Session::put('admin_id',$admin_id);
			$current_admin = $this -> getAdminName( $admin_id );
			Session::put('admin_name',$current_admin->name ); 
			// 权限信息
			$auths = DB::table('node_admin as na')
				-> select('n.controller','n.func')
				-> leftJoin('node as n','n.id','=','na.node_id')
				-> where('na.admin_id',$admin_id)
				-> get();
			$auth = array();
			foreach( $auths as $key => $info )
			{
				// 节点
				$auth[$key]['controller'] = $info -> controller;
				$auth[$key]['func'] = $info -> func;
			}
			Session::put('auths',$auth ); 
			
			
			// 2.  修改登录时间
			$res = 	DB::table('admin')
						->where( 'id','=',$admin_id )
						->update(['lasttime'=>date('Y-m-d H:i:s',time())]);
			
			// 3. 跳转到后台首页
			return redirect('/');
		}else
		{
			// 验证失败
			// 1. 回到登录页面
			return redirect('/login')->with( ['info'=>'请仔细检查账户或密码','name'=>$data['name'] ] );
		}
		
    }
	
	// 退出登录
	public function loginOut()
	{
		// 1. 清除session
		Session::forget('admin_id');
		Session::forget('admin_name');
		
		// 2. 跳转到登录页
		return redirect('/login');
	}
	
	
}
